package controllers

import (
	"../../../deps/lessgo/pagelet"
	"../../../deps/lessgo/utils"
	"../../../deps/lessgo/utilx"
	"../../base"
	"../../state"
	"../../store"
	"../schema"
	"io"
	"strconv"
	"time"
)

type Sys struct {
	*pagelet.Controller
}

func (c Sys) InfoAction() {

	c.AutoRender = false

	var rsp struct {
		ResponseJson
		Data schema.SysInfo `json:"data"`
	}
	rsp.ApiVersion = apiVersion
	rsp.Status = 400
	rsp.Message = "Bad Request"

	defer func() {
		if rspj, err := utils.JsonEncode(rsp); err == nil {
			io.WriteString(c.Response.Out, rspj)
		}
	}()

	sysKeeper, _ := store.Cmd("HGETALL", "sys:keeper").Hash()
	rsp.Data.Id = sysKeeper["id"]
	rsp.Data.Name = sysKeeper["name"]

	dbState, _ := store.Cmd("HMGET", "db:", "m", "n").List()
	rsp.Data.DataSize, _ = strconv.ParseInt(dbState[0], 10, 64)
	rsp.Data.DataKeyNum, _ = strconv.ParseInt(dbState[1], 10, 64)

	ledid := store.Cmd("GET", "sys:leader").String()
	rsp.Data.Version = store.Cmd("GET", "sys:keeper:ver").String()

	started := utilx.TimeParse(store.Cmd("GET", "sys:keeper:started").String(), "atom").Unix()
	rsp.Data.Uptime = time.Now().Unix() - started

	for _, v := range state.Peers {

		var osinfo utilx.Sysinfo
		store.Cmd("GET", "sys:ol:"+v.Id).Json(&osinfo)

		bpeer := base.Peer{
			Id:    v.Id,
			Addr:  v.Addr,
			Port:  v.Port,
			Proto: v.Proto,
		}

		rsp.Data.Peers = append(rsp.Data.Peers, schema.PeerInfo{
			Peer:   bpeer,
			OsInfo: osinfo,
		})

		if v.Id == ledid {
			rsp.Data.Leader = bpeer
		}
	}
	//rsp.Data.Uptime = utilx.TimeZoneFormat(state.Uptime, "Local", "atom")

	rsp.Status = 200
	rsp.Message = ""
}
